package com.hyphenate.easeui.widget.chatrow;

import android.content.Context;
import android.content.Intent;
import android.text.Spannable;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.TextView.BufferType;
import android.widget.Toast;

import com.czy.owner.R;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.WorkOrderDetailsModel;
import com.czy.owner.global.Constants;
import com.czy.owner.net.api.BaseResultEntity;
import com.czy.owner.net.utils.JsonUtil;
import com.czy.owner.net.utils.MyLoadView;
import com.czy.owner.ui.archive.TestingDetailsActivity;
import com.czy.owner.ui.workorder.BesPeakDetailsActivity;
import com.czy.owner.ui.workorder.OrderDetailsActivity3;
import com.czy.owner.utils.IntentUtils;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.easemob.cases.MessageHelper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMMessage.ChatType;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.easeui.utils.EaseSmileUtils;
import com.hyphenate.exceptions.HyphenateException;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.lang.reflect.Type;

public class EaseChatRowText extends EaseChatRow {

    private TextView contentView;
    protected MyLoadView mLoadView;
    public EaseChatRowText(Context context, EMMessage message, int position, BaseAdapter adapter) {
        super(context, message, position, adapter);

    }

    @Override
    protected void onInflatView() {
        inflater.inflate(message.direct() == EMMessage.Direct.RECEIVE ?
                R.layout.ease_row_received_message : R.layout.ease_row_sent_message, this);
    }

    @Override
    protected void onFindViewById() {
        contentView = (TextView) findViewById(R.id.tv_chatcontent);

    }

    @Override
    public void onSetUpView() {
        EMTextMessageBody txtBody = (EMTextMessageBody) message.getBody();
        Spannable span = EaseSmileUtils.getSmiledText(context, txtBody.getMessage());
        // 设置内容
        contentView.setText(span, BufferType.SPANNABLE);
        handleTextMessage();
    }

    protected void handleTextMessage() {
        if (message.direct() == EMMessage.Direct.SEND) {
            setMessageSendCallback();
            switch (message.status()) {
                case CREATE:
                    progressBar.setVisibility(View.GONE);
                    statusView.setVisibility(View.VISIBLE);
                    break;
                case SUCCESS:
                    progressBar.setVisibility(View.GONE);
                    statusView.setVisibility(View.GONE);
                    break;
                case FAIL:
                    progressBar.setVisibility(View.GONE);
                    statusView.setVisibility(View.VISIBLE);
                    break;
                case INPROGRESS:
                    progressBar.setVisibility(View.VISIBLE);
                    statusView.setVisibility(View.GONE);
                    break;
                default:
                    break;
            }
        } else {
            if (!message.isAcked() && message.getChatType() == ChatType.Chat) {
                try {
                    EMClient.getInstance().chatManager().ackMessageRead(message.getFrom(), message.getMsgId());
                } catch (HyphenateException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    protected void onUpdateView() {
        adapter.notifyDataSetChanged();
    }

    @Override
    protected void onBubbleClick() {
        MyLog.e("hep", message.getStringAttribute(MessageHelper.MESSAGE_EXT_CUSTOM_TYPE, null) + "--" + message.getStringAttribute(MessageHelper.MESSAGE_EXT_DATA, null));
        try {
            // TODO 跳转至订单详情页inspectionOrder
            if ("order".equals(message.getStringAttribute(MessageHelper.MESSAGE_EXT_CUSTOM_TYPE, null))) {
                String data = message.getStringAttribute(MessageHelper.MESSAGE_EXT_DATA, null);
                String orderStatus = JsonUtil.getJsonValuesString(data, "orderType");
                if ("serviceOrder".endsWith(orderStatus)) {
                    String orderNumber = JsonUtil.getJsonValuesString(data, "orderNumber");
                    String userOrderId = JsonUtil.getJsonValuesString(data, "userOrderId");
//                String orderStatus = JsonUtil.getJsonValuesString(data, "orderStatus");
//                String openTime = JsonUtil.getJsonValuesString(data, "openTime");
                    getData(orderNumber, userOrderId);
                } else if ("inspectionOrder".endsWith(orderStatus)) {
                    String userOrderId = JsonUtil.getJsonValuesString(data, "userOrderId");
                    String storeId = JsonUtil.getJsonValuesString(data, "storeId");
                    context.startActivity(new Intent(context, TestingDetailsActivity.class).putExtra("storeId", storeId).putExtra("userOrderId", userOrderId));
                }
                // TODO 跳转至公告
            } else if ("bulletin".equals(message.getStringAttribute(MessageHelper.MESSAGE_EXT_CUSTOM_TYPE, null))) {
                String data = message.getStringAttribute(MessageHelper.MESSAGE_EXT_DATA, null);
                String infoId = JsonUtil.getJsonValuesString(data, "infoId");
                IntentUtils.startBulletin(context, infoId);
            }
        } catch (Exception e) {


            Toast.makeText(context, "参数异常", Toast.LENGTH_SHORT).show();
        }
    }

    //获取工单
    private void getData(String orderNumber, final String userOrderId) {
        if (mLoadView == null)
            mLoadView = new MyLoadView(context, "正在加载");

        mLoadView.ShowLoadView();
        String url = Constants.APP_API_BASE + Constants.OWN_SHOP_MYORDERINF;
        RequestParams params = new RequestParams(url);
        params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(context).getSession());
        params.addBodyParameter("orderNumber", orderNumber);
        x.http().post(params, new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(String result) {
                Gson gson = new Gson();
                Type type = new TypeToken<BaseResultEntity<WorkOrderDetailsModel>>() {
                }.getType();
                BaseResultEntity<WorkOrderDetailsModel> model = gson.fromJson(result, type);
                if (model.isFlag()) {
                    if (model.getData().getOrderStatus().equals("waitPayDeposit") || model.getData().getOrderStatus().equals("waitService")) {
                        Intent ti = new Intent(context, BesPeakDetailsActivity.class);
                        ti.putExtra("orderNumber", model.getData().getOrderNumber());
                        ti.putExtra("userOrderId", userOrderId);
                        ti.putExtra("isMessage", true);
                        context.startActivity(ti);
                    } else if (model.getData().getOrderStatus().equals("cancelled") && model.getData().getOpenTime().equals("0")) {
                        Intent ti = new Intent(context, BesPeakDetailsActivity.class);
                        ti.putExtra("orderNumber", model.getData().getOrderNumber());
                        ti.putExtra("userOrderId", userOrderId);
                        ti.putExtra("isMessage", true);
                        context.startActivity(ti);
                    } else {
                        Intent ti = new Intent(context, OrderDetailsActivity3.class);
                        ti.putExtra("orderNumber", model.getData().getOrderNumber());
                        ti.putExtra("userOrderId", userOrderId);
                        ti.putExtra("isMessage", true);
                        context.startActivity(ti);
                    }
                } else {
                    PhoneUtils.ShowToastMessage(context, model.getExp());
                }


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                mLoadView.CancleLoadView();
            }
        });
    }
}
